package com.the_ring.chapter04.three;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


import androidx.appcompat.app.AppCompatActivity;


import com.the_ring.chapter04.R;

public class MainActivity extends AppCompatActivity {

    TextView messageTv;

    AReceiver aReceiver;
    BReceiver bReceiver;

    private String RECEIVER_ACTION = "com.thering.filter";

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third_main);

        aReceiver = new AReceiver();
        IntentFilter aFilter = new IntentFilter(RECEIVER_ACTION);
//        aFilter.setPriority(10);
        registerReceiver(aReceiver, aFilter);

        bReceiver = new BReceiver();
        IntentFilter bFilter = new IntentFilter(RECEIVER_ACTION);
//        bFilter.setPriority(12);
        registerReceiver(bReceiver, bFilter);

        messageTv = findViewById(R.id.tv_message);

        findViewById(R.id.bt_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(RECEIVER_ACTION);
                sendOrderedBroadcast(intent, null);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(aReceiver);
        unregisterReceiver(bReceiver);
    }

    public class AReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String str = messageTv.getText().toString();
            messageTv.setText(str + "A 收到广播\n");

        }
    }

    public class BReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String str = messageTv.getText().toString();
            messageTv.setText(str + "B 收到广播");
            abortBroadcast();
        }
    }
}